<template>
	<view>

		<view class="u-flex u-flex-wrap listBox ">
			<view v-for="(item,index) in temp" :key="index" class="" :style="[wrapStyle]">

				<view @click.stop="close(index)" class="close">
					<texat style="color: #fff;text-align: center;font-size: 10rpx;margin-left: 7rpx;margin-bottom: 10rpx;">x</texat>
				</view>
			
				<u-image @click="preView(index)" :src="item" v-if="uploadType=='Image'" :width="width" :height="height">
				</u-image>
				<video :show-fullscreen-btn="false" :id="'video_play'+index" object-fit="cover" :src="item" v-else
					:style="[wrapStyle]" @fullscreenchange="fullscreenchange" @play="playVedio(index)"></video>
			</view>

	

			<view v-if="temp.length!==number" style="position: relative;" @click="upload" class="  " :style="[wrapStyle]">
				<view class="content">
					<u-icon :name="iconName" :size="iconSize"></u-icon>
					<view class="" style="font-size: 22rpx;" v-if="!text">
						{{uploadType=='Image'?'添加照片':'添加视频'}}
					</view>
					<view class="" style="font-size: 22rpx;" v-else>
						{{text}}
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import baseUrl from '@/common/baseUrl.js';
	export default {
		name: "w-upload",
		props: {
			value: {
				type: [String, Array],
				// default:''
				// default: () => []
			},
			// 图标
			iconName: {
				type: [String, Number],
				default: 'photo'
			},
			text: {
				type: [String, Number],
				default: ''
			},
			//图标大小
			iconSize: {
				type: [String, Number],
				default: '50'
			},
			// 宽度，单位任意
			width: {
				type: [String, Number],
				default: '200'
			},
			// 高度，单位任意
			height: {
				type: [String, Number],
				default: '200'
			},
			// 背景
			background: {
				type: [String, Number],
				default: '#fff'
			},
			// 圆角
			borderRadius: {
				type: [String, Number],
				default: 0
			},
			// 上传类型
			uploadType: {
				type: [String, Number],
				default: "Image"
			},
			//裁剪名字
			cropName: {
				type: [String, Number],
				default: ""
			},
			// 图片宽度
			destWidth:{
				type: [String, Number],
				default: "300"
			},
			// 剪框宽度
			rectWidth:{
				type: [String, Number],
				default: "300"
			},
			number:{
				type: Number,
				default: 6
			},
		},
		watch: {
			value: {
				immediate: true,
				handler(v) {
					
					if(Array.isArray(v)){
						this.temp = v;
					}else{
						if(v){
							this.temp = v.split(',');
						}else{
							this.temp = [];
						}
					}
					
				}
			}
		},
		computed: {
			wrapStyle() {
				let style = {};
				// 通过调用addUnit()方法，如果有单位，如百分比，px单位等，直接返回，如果是纯粹的数值，则加上rpx单位
				style.width = this.$u.addUnit(this.width);
				style.height = this.$u.addUnit(this.height);
				style.background = this.background;
				// 如果是配置了圆形，设置50%的圆角，否则按照默认的配置值
				style.borderRadius = this.$u.addUnit(this.borderRadius);
				// 如果设置圆角，必须要有hidden，否则可能圆角无效
				style.overflow = this.borderRadius > 0 ? 'hidden' : 'visible';
				return style;
			}
		},
		data() {
			return {
				temp: [],
				videoContext: '',
				
			}
		},
		created() {
			// 监听从裁剪页发布的事件，获得裁剪结果
			uni.$on('uAvatarCropper', path => {
				if(this.cropName && uni.getStorageSync("cropName")==this.cropName){
					this.netUpload(path);
					uni.removeStorageSync('cropName')
				}
			})
		},

		methods: {
			preView(index) {
				uni.previewImage({
					urls: this.temp,
					current: index
				})
			},
			close(index) {
				console.log(index,777)
				this.temp.splice(index, 1);
				this.emitInput(this.temp)
			},
			fullscreenchange(e) {
				if (!e.detail.fullScreen) {
					this.videoContext.stop()
				}
			},
			playVedio(index) {
				this.videoContext = uni.createVideoContext(`video_play${index}`, this);
				this.videoContext.requestFullScreen();
			},
			crop() {
				uni.setStorageSync('cropName',this.cropName);
				this.$u.route({
					// 关于此路径，请见下方"注意事项"
					url: '/uview-ui/components/u-avatar-cropper/u-avatar-cropper',
					// 内部已设置以下默认参数值，可不传这些参数
					params: {
						// 输出图片宽度，高等于宽，单位px
						destWidth: this.destWidth,
						// 裁剪框宽度，高等于宽，单位px
						rectWidth: this.rectWidth,
						// 输出的图片类型，如果'png'类型发现裁剪的图片太大，改成"jpg"即可
						fileType: 'jpg',
					}
				})
			},
			upload() {
				if (this.cropName) {
					this.crop()
					return false;
				}
				if (this.uploadType == 'Image') {
					uni.chooseImage({
						sizeType: ['compressed'],
						sourceType: ["album"],
						sourceType: ['camera', 'album'], //从相册选择
						count: 1,
						success: res => {
							let path = res.tempFiles[0].path;
							let size = res.tempFiles[0].size;
							this.netUpload(path)
						}
					})
				} else {
					uni.chooseMedia({
						count: 1,
						mediaType: ["video"],
						sizeType: ['compressed'],
						sourceType: ['camera', 'album'], //从相册选择
						success: res => {
							let videoInfo = {
								path: res.tempFiles[0].tempFilePath,
								size: res.tempFiles[0].size,
								duration: res.tempFiles[0].duration,
								height: res.tempFiles[0].height,
								width: res.tempFiles[0].width,
								thumbTempFilePath: res.tempFiles[0].thumbTempFilePath,
							}
							this.netUpload(videoInfo.path)
						},
						fail: err => {

						}
					})
				}
			},
			netUpload(url) {
				return new Promise((resolve, reject) => {
					let uploadType = this.uploadType == 'Image' ? '/api/index/uploadImage' :
						'/api/index/uploadVideo';
					let uploadName = this.uploadType == 'Image' ? 'file' : 'video';
					const uploadTask = uni.uploadFile({
						url: baseUrl.url + uploadType,
						filePath: url,
						name: uploadName,
						success: res => {
							var Data = JSON.parse(res.data);
							var fileUrl = Data.data[0];
							
							if(Array.isArray(this.temp)){
								this.temp.push(fileUrl)
							}else{
								this.temp = this.temp ? this.temp + ',' + fileUrl : fileUrl;
							}
							
							this.emitInput(this.temp.join(','))
						}
					})

					uploadTask.onProgressUpdate((res) => {

						uni.showLoading({
							title: "上传中"
						})
						if (res.progress == 100) {
							
							uni.hideLoading({

							})
						}

					})

				})
			},
			emitInput(value) {
				
				this.$emit('input', value);
			},
		}

	}
</script>

<style scoped lang="scss">
	.listBox {
		padding: 0rpx 20rpx 20rpx 20rpx;
	}

	.listBox>view {
		margin-right: 30rpx;
		margin-top: 30rpx;
		position: relative;
		border: 1rpx dashed #bdbdbd;
	}

	.close {
		position: absolute;
		    top: 0;
		    right: 0;
		    background-color: #373737;
		    height: 28rpx;
		    width: 28rpx;
		    display: flex;
		    flex-direction: row;
		    border-bottom-left-radius: 200rpx;
		    align-items: center;
		    justify-content: center;
		    z-index: 3;
	
	}

	.content {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		text-align: center;
	}
</style>
